package com.just_bean.core.aop;

import com.just_bean.core.handler.JustMethodProxy;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.util.ArrayList;
import java.util.List;

public class CgLibClz extends AopClz {
    private Enhancer enhancer;

    public CgLibClz(Class clz) {
        super(clz);
        this.enhancer = new Enhancer();
        this.enhancer.setSuperclass(clz);
        // 设置代理类的函数执行
        this.enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
            List<JustMethodProxy> list = this.aopMap.getOrDefault(method, new ArrayList<>());
            // 执行该函数的切面前置操作
            for (JustMethodProxy callback : list) {
                callback.pre(method, clz, o, objects);
            }
            // 执行代理类原函数
            Object result = methodProxy.invokeSuper(o, objects);
            // 执行该函数的切面后置操作
            for (JustMethodProxy callback : list) {
                result = callback.after(method, clz, o, objects, result);
            }
            return result;
        });
    }

    @Override
    public Object newInstance() {
        return enhancer.create();
    }
}
